package com.code.bolg.service.impl;

import com.code.bolg.bean.Role;
import com.code.bolg.bean.RoleMenu;
import com.code.bolg.enums.DelFlagEnum;
import com.code.bolg.enums.ResultEnum;
import com.code.bolg.exception.BolgExcetion;
import com.code.bolg.repository.RoleMenuRepository;
import com.code.bolg.service.RoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class RoleMenuServiceImpl implements RoleMenuService {
    @Autowired
    private RoleMenuRepository roleMenuRepository;

    EntityManager entityManager;

    @Override
    public RoleMenu save(RoleMenu role) {
        RoleMenu save = roleMenuRepository.save(role);
        return save;
    }

    @Override
    public int deleteById(int id) {
        Optional<RoleMenu> optional= roleMenuRepository.findById(id);
        if(optional.isPresent()){
            roleMenuRepository.deleteById(id);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public RoleMenu findById(int id) {
        Optional<RoleMenu> optional = roleMenuRepository.findById(id);
        if (optional.isPresent()) {
            RoleMenu menu = optional.get();
            return menu;
        } else {
            throw new BolgExcetion(ResultEnum.NOTFINDDATA);
        }
    }

    @Override
    public List<RoleMenu> findAll(RoleMenu menu, int page, int size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        //分页构造
        Pageable pageable = PageRequest.of(page,size,sort);
        Example<RoleMenu> example = Example.of(menu);
        Page<RoleMenu> all = roleMenuRepository.findAll(example,pageable);
        return  all.getContent();
    }


    @Override
    public List<RoleMenu> findAll(int page, int size) {
        RoleMenu s = new RoleMenu();
        s.setDelFlag(DelFlagEnum.NOTDELETE.getCode());
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        //分页构造
        Pageable pageable = PageRequest.of(page,size,sort);
        Example<RoleMenu> example = Example.of(s);
        Page<RoleMenu> all = roleMenuRepository.findAll(example,pageable);
        return  all.getContent();
    }
}
